import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { verifyToken } from './lib/auth-service'

// 定义需要管理员权限的路径
const adminPaths = [
  '/admin',
  '/admin/tools',
  '/api/admin'
]

export function middleware(request: NextRequest) {
  const { pathname } = request.nextUrl

  // 检查是否是管理员路径
  const isAdminPath = adminPaths.some(path => 
    pathname === path || pathname.startsWith(path + '/') || pathname.startsWith(path + '?')
  )

  if (isAdminPath) {
    // 从 cookie 获取认证 token
    const token = request.cookies.get('auth-token')?.value
    
    if (!token) {
      // 没有 token，重定向到登录页
      const url = request.nextUrl.clone()
      url.pathname = '/login'
      return NextResponse.redirect(url)
    }

    try {
      // 验证 token
      const user = verifyToken(token)
      
      if (!user || user.role !== 'ADMIN') {
        // 不是管理员，重定向到主页
        const url = request.nextUrl.clone()
        url.pathname = '/'
        return NextResponse.redirect(url)
      }
      
      // 管理员用户，允许访问
      return NextResponse.next()
    } catch (error) {
      // token 无效，重定向到登录页
      const url = request.nextUrl.clone()
      url.pathname = '/login'
      return NextResponse.redirect(url)
    }
  }

  // 非管理员路径，正常处理
  return NextResponse.next()
}

// 配置中间件匹配的路径
export const config = {
  matcher: [
    '/admin/:path*',
    '/api/admin/:path*'
  ]
}